package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.AppSendMessageService;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.service.OSSService;
import com.easylinkin.linkappapi.common.utils.file.FileExt;
import com.easylinkin.linkappapi.common.utils.file.ZipFileUtil;
import com.easylinkin.linkappapi.common.utils.message.AppSendMessageUtil;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage.model;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage.type;
import com.easylinkin.linkappapi.facerecognition.service.oss.ObjectStorageInternalService;
import com.easylinkin.linkappapi.messagecenter.entity.MessageCenter;
import com.easylinkin.linkappapi.messagecenter.entity.enumType.messageTypeEnum;
import com.easylinkin.linkappapi.messagecenter.service.MessageCenterService;
import com.easylinkin.linkappapi.photoalbum.util.ExportUtil;
import com.easylinkin.linkappapi.quality.dto.QualityAppraisingExcellentDTO;
import com.easylinkin.linkappapi.quality.dto.QualityAppraisingExcellentPhotoAlbumDTO;
import com.easylinkin.linkappapi.quality.dto.QualityAppraisingExcellentPhotoAlbumQueryDTO;
import com.easylinkin.linkappapi.quality.entity.ProblemType;
import com.easylinkin.linkappapi.quality.entity.QualityAppraisingExcellent;
import com.easylinkin.linkappapi.quality.entity.QualityPosition;
import com.easylinkin.linkappapi.quality.mapper.QualityAppraisingExcellentMapper;
import com.easylinkin.linkappapi.quality.service.ProblemTypeService;
import com.easylinkin.linkappapi.quality.service.QualityAppraisingExcellentService;
import com.easylinkin.linkappapi.quality.service.QualityPositionService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 质量评优信息 服务实现类
 * </p>
 *
 * @author Xiaoyang
 * @since 2022-09-01
 */
@Slf4j
@Service
public class QualityAppraisingExcellentServiceImpl extends
    ServiceImpl<QualityAppraisingExcellentMapper, QualityAppraisingExcellent> implements
    QualityAppraisingExcellentService {

  @Resource
  private CommonService commonService;
  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Resource
  private QualityPositionService qualityPositionService;
  @Resource
  private ProblemTypeService problemTypeService;
  @Autowired
  private AppSendMessageService appSendMessageService;

  @Override
  public boolean saveOne(QualityAppraisingExcellent qualityAppraisingExcellent) {
    if(StringUtils.isNotEmpty(qualityAppraisingExcellent.getNoticerIds())){
      List<String> userIds = Arrays.asList(qualityAppraisingExcellent.getNoticerIds().split(","));
      Assert.isTrue(userIds.size()<=10, "通知人最多只能选10人");
    }
    commonService.setCreateAndModifyInfo(qualityAppraisingExcellent);
    commonService.setTenantIdInfo(qualityAppraisingExcellent);
    qualityAppraisingExcellent.setDeleteState(1);
    boolean flag = save(qualityAppraisingExcellent);
    if(flag){
      // 质量评优提醒 消息推送
      // 发送消息通知人
      if(StringUtils.isNotEmpty(qualityAppraisingExcellent.getNoticerIds())){
        QualityPosition qualityPosition = qualityPositionService
            .getById(qualityAppraisingExcellent.getCheckPartId());
        ProblemType problemType = problemTypeService
            .getById(qualityAppraisingExcellent.getProblemTypeId());
        StringBuilder sb = new StringBuilder();
        sb.append(qualityPosition.getFullName());
        sb.append(" ").append(problemType.getFullName())
            .append(" ").append(qualityAppraisingExcellent.getContent());
        String title = "质量评优提醒";
        List<String> userIds = Arrays.asList(qualityAppraisingExcellent.getNoticerIds().split(","));
        userIds.forEach(p -> {
          // 消息中心
          saveMessage(title, sb.toString(),
              p, qualityAppraisingExcellent.getId().toString(),true);
        });
      }
    }

    return flag;
  }

  @Autowired
  private MessageCenterService messageCenterService;

  /**
   * 发送消息
   *
   * @param content 消息内容
   * @param ownerId 消息接收人/所属人
   */
  public void saveMessage(String title, String content, String ownerId, String linkId, Boolean isPushJG) {

    MessageCenter messageCenter = new MessageCenter();
    messageCenter.setTenantId(linkappUserContextProducer.getCurrent().getTenantId());
    messageCenter.setContent(content);
    messageCenter.setOwnerId(ownerId);
    messageCenter.setType(messageTypeEnum.QUALITY_APPRAISING_EXCELLENT.ordinal());
    messageCenter.setSelf(false);
    messageCenter.setStatus(0);
    messageCenter.setTitle(title);
    messageCenter.setCreateTime(new Date());
    messageCenter.setLinkId(linkId);

    messageCenterService.saveOne(messageCenter);

    if(isPushJG){
      // 手机推送
      appSendMessageService
          .pushMessageToPhone(messageCenter.getId().toString(), model.QUALITY_APPRAISING_EXCELLENT, type.MSG,
              ownerId, title, content);
    }


  }

  @Override
  public IPage<QualityAppraisingExcellentDTO> selectDtoPage(Page page,
      QualityAppraisingExcellentDTO customQueryParams) {
    customQueryParams.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    return baseMapper.selectDtoPage(page,customQueryParams);
  }

  @Override
  public QualityAppraisingExcellentDTO findById(Long id) {
    QualityAppraisingExcellentDTO qualityAppraisingExcellentDTO = new QualityAppraisingExcellentDTO();
    qualityAppraisingExcellentDTO.setId(id);
    IPage<QualityAppraisingExcellentDTO> iPage = this.selectDtoPage(new Page<>(0, 1), qualityAppraisingExcellentDTO);
    if (iPage.getRecords().size() > 0) {
      qualityAppraisingExcellentDTO = iPage.getRecords().get(0);
    }
    return qualityAppraisingExcellentDTO;
  }

  @Override
  public IPage<QualityAppraisingExcellentPhotoAlbumDTO> selectPhotoAlbumByPage(Page page,
      QualityAppraisingExcellentPhotoAlbumQueryDTO queryDTO) {
    Integer enterpriseSourceType = queryDTO.getEnterpriseSourceType();
    if(enterpriseSourceType == null || enterpriseSourceType.intValue() == 1){
      queryDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
    IPage<QualityAppraisingExcellentPhotoAlbumDTO> pagelist = baseMapper
        .selectPhotoAlbumByPage(page, queryDTO);
    pagelist.getRecords().forEach(p->setPhotos(p));
    return pagelist;
  }

  private void setPhotos(QualityAppraisingExcellentPhotoAlbumDTO dto){
    List<String> photos = new ArrayList<>();
    String imgs = dto.getImgs();
    if(StringUtils.isNotEmpty(imgs)){
      photos.addAll(Arrays.asList(imgs.split(",")));
    }
    dto.setPhotos(photos);
  }

  @Override
  public int photoAlbumCount(QualityAppraisingExcellentPhotoAlbumQueryDTO queryDTO) {
    //项目id 过滤
    queryDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<QualityAppraisingExcellentPhotoAlbumDTO> list = baseMapper
        .selectPhotoAlbumByPage(queryDTO);
    int total = 0;
    if(CollectionUtil.isNotEmpty(list)){
      for (QualityAppraisingExcellentPhotoAlbumDTO dto : list) {
        setPhotos(dto);
        if(CollectionUtil.isNotEmpty(dto.getPhotos())){
          total += dto.getPhotos().size();
        }
      }
    }
    return total;
  }

  @Autowired
  @Qualifier("ossInternal")
  private ObjectStorageInternalService ossClient;

  @Autowired
  private OSSService ossService;

  @Value("${oss.dir}")
  private String dir;

  @Value("${oss.bucket}")
  private String bucket;

  @Value("${oss.readHost}")
  private String readHost;

  private final String prefix = "质量评优";

  @Override
  public String exportPhotoAlbum(QualityAppraisingExcellentPhotoAlbumQueryDTO dto) {
    //项目id 过滤
    dto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    String fileName = null;
    List<QualityAppraisingExcellentPhotoAlbumDTO> list = baseMapper
        .selectPhotoAlbumByPage(dto);

    List<FileExt> fileExtList = new ArrayList<>();
    if(CollectionUtil.isNotEmpty(list)){

      int total = 0;
      if(CollectionUtil.isNotEmpty(list)){
        for (QualityAppraisingExcellentPhotoAlbumDTO p : list) {
          setPhotos(p);
          if(CollectionUtil.isNotEmpty(p.getPhotos())){
            total += p.getPhotos().size();
          }
        }
      }
      if(total > 100){
        throw new RuntimeException("相册导出失败！相册导出不能超过100张");
      }

      for (QualityAppraisingExcellentPhotoAlbumDTO p : list) {
        List<String> photos = p.getPhotos();
        if (CollectionUtil.isNotEmpty(photos)) {
          List<String> fileUrlList = new ArrayList<>();
          for (int i = 0; i < photos.size(); i++) {
            String singleFile = photos.get(i);
            fileUrlList.add(singleFile);
          }
          long count = 0;
          for (String url : fileUrlList) {

            if (StringUtils.isNotEmpty(url)) {
              url = url.replace("+", "%2B");
              url = url.replace("&", "%26");
            } else {
              log.error("打包失败：名称为空");
              continue;
            }
            FileExt fileInfoByUrl = ExportUtil
                .getFileInfoByUrl(url,prefix, com.easylinkin.linkappapi.common.utils.DateUtil.getyyyyMMddHHmmssSSSNumberString(p.getCreateTime()),p.getProblemTypeFullName(),count);
            if (null != fileInfoByUrl && null != fileInfoByUrl.getInputStream()) {
              fileExtList.add(fileInfoByUrl);
              count ++;
            } else {
              log.error("打包失败：名称【{}】", url);
            }
          }
        }
      }

    }


    //开始导出
    InputStream fileInputStream = null;
    try {
      String today = com.easylinkin.linkappapi.common.utils.DateUtil.getyyyyMMddHHmmssSSSNumberString(new Date());
      fileInputStream = ZipFileUtil.getFileInputStream(today, fileExtList);
      //上传文件到oss
      String resultFilename =
          prefix + "_" + today + ".zip";
      ossClient.putObject(bucket, resultFilename, fileInputStream, "application/octet-stream");
      fileName = ossService.generateUrl(resultFilename);
    } catch (Exception e) {
      log.error("打包失败：", e);
    } finally {
      // 关闭流
      try {
        if (null != fileInputStream) {
          fileInputStream.close();
        }
      } catch (IOException e) {
        log.error("打包失败：", e);
      }
    }
    return fileName;
  }
}
